#include "AddMouldWidget.h"
#include "./ui_AddMouldWidget.h"
#include <QKeyEvent>
#include "../database/DatabaseManager.h"
#include <QMessageBox>
#include <QTimer>

AddMouldWidget::AddMouldWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AddMouldWidget)
{
    ui->setupUi(this);
    setFocusPolicy(Qt::StrongFocus);
    setFocusProxy(ui->lineEdit);
    ui->lineEdit->setFocus();

    ui->lineEdit->installEventFilter(this);
    ui->lineEdit_2->installEventFilter(this);
    ui->lineEdit_3->installEventFilter(this);
}

bool AddMouldWidget::eventFilter(QObject *obj, QEvent *ev)
{
    if ((obj == ui->lineEdit || obj == ui->lineEdit_2 || obj == ui->lineEdit_3)
        && ev->type() == QEvent::KeyPress)
    {
        auto *ke = static_cast<QKeyEvent*>(ev);
        if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) {
            focusNextChild();
            return true;
        }
    }
    return QWidget::eventFilter(obj, ev);
}

void AddMouldWidget::on_pushButton_clicked()
{
    DatabaseManager &manager = DatabaseManager::getInstance();
    if (ui->lineEdit->text().isEmpty() || ui->lineEdit_2->text().isEmpty() || ui->lineEdit_3->text().isEmpty()) {
        QMessageBox::warning(this, tr("输入错误"), tr("输入框不能为空！"));
        return;
    }
    QString mouldName = ui->lineEdit->text();
    QString upperCode = ui->lineEdit_2->text();
    QString lowerCode = ui->lineEdit_3->text();

    if (!manager.isConnected()) {
        QMessageBox::critical(this, tr("错误"), tr("数据库未连接！"));
        return;
    }

    QSqlQuery q(manager.m_database);

    // 2) 先查是否已存在此 mould_code
    int mouldId = -1;
    q.prepare("SELECT id FROM Mould WHERE mould_code = ?");
    q.addBindValue(mouldName);
    if (!q.exec()) {
        QMessageBox::critical(this, tr("错误"), tr("查询失败：%1").arg(q.lastError().text()));
        return;
    }
    if (q.next()) {
        mouldId = q.value(0).toInt();
        // 弹确认框
        const auto ret = QMessageBox::question(
            this, tr("记录已存在"),
            tr("模具编号 \"%1\" 已存在，是否覆盖？").arg(mouldName),
            QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
        if (ret == QMessageBox::No) {
            ui->lineEdit->clear();
            ui->lineEdit_2->clear();
            ui->lineEdit_3->clear();
            // 让焦点回到第一个输入框
            QTimer::singleShot(0, ui->lineEdit, [this]{ ui->lineEdit->setFocus(Qt::TabFocusReason); });
            return;
        }
    }
    // 3) 事务开始
    if (!manager.m_database.transaction()) {
        QMessageBox::critical(this, tr("错误"), tr("开启事务失败：%1").arg(manager.m_database.lastError().text()));
        return;
    }

    auto getOrCreateSideId = [&](const QString &code) -> int {
        QSqlQuery qq(manager.m_database);
        // 3.1 先插入（若已存在则忽略）
        qq.prepare("INSERT OR IGNORE INTO SidePlate(sideplate_code) VALUES(?)");
        qq.addBindValue(code);
        if (!qq.exec()) return -1;

        // 3.2 再查询 id
        qq.prepare("SELECT id FROM SidePlate WHERE sideplate_code = ?");
        qq.addBindValue(code);
        if (!qq.exec()) return -1;
        if (!qq.next())  return -1;
        return qq.value(0).toInt();
    };

    const int upId   = getOrCreateSideId(upperCode);
    const int downId = getOrCreateSideId(lowerCode);
    if (upId <= 0 || downId <= 0) {
        manager.m_database.rollback();
        QMessageBox::critical(this, tr("错误"), tr("获取侧板ID失败。"));
        return;
    }

    bool ok = false;
    if (mouldId > 0) {
        // 4) 覆盖：更新已存在的模具行
        q.prepare("UPDATE Mould SET upper_id = ?, lower_id = ? WHERE id = ?");
        q.addBindValue(upId);
        q.addBindValue(downId);
        q.addBindValue(mouldId);
        ok = q.exec();
    } else {
        // 5) 新增：插入模具
        q.prepare("INSERT INTO Mould (mould_code, upper_id, lower_id) VALUES (?, ?, ?)");
        q.addBindValue(mouldName);
        q.addBindValue(upId);
        q.addBindValue(downId);
        ok = q.exec();
    }

    if (!ok) {
        manager.m_database.rollback();
        QMessageBox::critical(this, tr("错误"), tr("保存失败：%1").arg(q.lastError().text()));
        return;
    }

    if (!manager.m_database.commit()) {
        manager.m_database.rollback();
        QMessageBox::critical(this, tr("错误"), tr("提交事务失败：%1").arg(manager.m_database.lastError().text()));
        return;
    }
    ui->lineEdit->clear();
    ui->lineEdit_2->clear();
    ui->lineEdit_3->clear();
    ui->lineEdit->setFocus();
}

